package com.planw.beetl.action

import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.QueryExecutorBase
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiMethod
import com.intellij.psi.search.searches.DefinitionsScopedSearch
import com.intellij.util.Processor
import com.planw.beetl.sql.search.BeetlSqlJavaMapperQueryExecutorBase
import org.jetbrains.kotlin.asJava.toLightClass
import org.jetbrains.kotlin.asJava.toLightMethods
import org.jetbrains.kotlin.psi.KtClass
import org.jetbrains.kotlin.psi.KtNamedFunction

open class KotlinMapperDefinitionsScopedSearch : QueryExecutorBase<PsiElement, DefinitionsScopedSearch.SearchParameters>() {

    override fun processQuery(searchParameters: DefinitionsScopedSearch.SearchParameters, consumer: Processor<in PsiElement>) {
        if (ApplicationManager.getApplication().isReadAccessAllowed) {
            toSearchSql(searchParameters, consumer)
        } else {
            ApplicationManager.getApplication().runReadAction({
                toSearchSql(searchParameters, consumer)
            })
        }
    }

    fun toSearchSql(searchParameters: DefinitionsScopedSearch.SearchParameters, consumer: Processor<in PsiElement>) {
        var psMethod: PsiMethod? = null;
        if (searchParameters.element is KtNamedFunction) {
            val methods = searchParameters.element.toLightMethods()
            if (methods != null && methods.isNotEmpty()) {
                psMethod = methods[0]
            }
        }
        if (searchParameters.element is PsiMethod) {
            psMethod = searchParameters.element as PsiMethod
        }
        psMethod?.let {
            BeetlSqlJavaMapperQueryExecutorBase.toSearchSql(it, consumer)
        }
        var psiClas: PsiClass? = null
        if (searchParameters.element is KtClass) {
            psiClas = (searchParameters.element as KtClass).toLightClass()
        }
        if (searchParameters.element is PsiClass) {
            psiClas = searchParameters.element as PsiClass
        }
        psiClas?.let {
            BeetlSqlJavaMapperQueryExecutorBase.toSearchSqlByClass(it, consumer)
        }
    }

}